﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using S.BreedingHistory.Api.Application.Commmand;
using S.BreedingHistory.Api.Dto;
using S.BreedingHistory.Domain.Model;
using S.BreedingHistory.Infrastructure.Interface;
using S.Common.helper;

namespace S.BreedingHistory.Api.Application.CommmandHandler
{
    public class BreedHistoryBatchUpdateCommandHandler : IRequestHandler<BreedHistoryBatchUpdateCommand, bool>
    {
        private readonly IBreedingHistoryRepository breedingHistoryRepository;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IMapper mapper;

        public BreedHistoryBatchUpdateCommandHandler(IBreedingHistoryRepository breedingHistoryRepository,IHttpContextAccessor httpContextAccessor,IMapper mapper,IConfiguration configuration)
        {
            this.breedingHistoryRepository = breedingHistoryRepository;
            this.httpContextAccessor = httpContextAccessor;
            this.mapper = mapper;
         
        }
        /// <summary>
        /// 批量修改种母历史记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(BreedHistoryBatchUpdateCommand request, CancellationToken cancellationToken)
        {
            int isOk = 0;
            foreach (var item in request.breedingHistoryModels)
            {
                string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
                if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer"))
                {
                    authHeader = authHeader.Substring("Bearer ".Length).Trim();
                }
                BreedingHistoryModel breedingHistoryModel = mapper.Map<BreedingHistoryModel>(item);
            }
            return await breedingHistoryRepository.BatchUpdateBreedHistory(request.breedingHistoryModels);
        }
    }
}
